/**
 * 
 */
package com.bridgetree.jubaocrm.ui.groups;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.Contents;
import com.bridgetree.jubaocrm.ui.LoginUtil;
import com.bridgetree.jubaocrm.ui.PageProjectAdapter;
import com.bridgetree.jubaocrm.ui.ProgressDialogUtil;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshBase.OnRefreshListener;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshListView;
import com.bridgetree.jubaocrm.util.Groups;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.Projects;
/**
 * GroupsAnnouncementActivity </p> 项目公海 2014-5-20 上午11:21:00 create
 * 
 * @since 1.0
 */
public class GroupsHaiListActivity extends Activity {
	private final String TAG = "GroupsAnnouncementActivity";

	private Context mContext;

	private Groups mGroups;

	private String user_id = "";

	private String token = "";

	private ArrayList<Projects> mProjectsList;

	private int scrollTopBottomma = 0;

	// private int mAnnouncementListSizema =0;
	private int pageIndexma = 1;

	private PageProjectAdapter mRuAdapter2;

	private PullToRefreshListView firstcategory2 = null;
	private ListView actualListView2 = null;

	private int scrollTopBottompr = 0;

	private int pageIndexpr = 1;

	private int projectLastPos = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.group_project);
		mContext = this;
		Intent intent = getIntent();
		if(intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, "");
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");

		TextView xm_bi_tv_title = (TextView) findViewById(R.id.xm_bi_tv_title);
		if(intent.getExtras() != null) {
			mGroups = (Groups) intent.getExtras().getSerializable("groupsMain");
		}
		xm_bi_tv_title.setText("项目公海");
	
		findViewById(R.id.xm_bi_RelativeLayout_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		firstcategory2 = (PullToRefreshListView)findViewById(R.id.firstcategoryXM);
		firstcategory2.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				if(scrollTopBottompr == 1){
					pageIndexpr++;
					if (mGroups != null) {
						getProjects(pageIndexpr);
					}
				}else if(scrollTopBottompr == 0){
					pageIndexpr=1;
					if (mGroups != null) {
						getProjects(pageIndexpr);
					}
				}
			}
		});

		firstcategory2.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
					projectLastPos= firstcategory2.getRefreshableView().getLastVisiblePosition();
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				if (firstVisibleItem + visibleItemCount == totalItemCount) {
					scrollTopBottompr = 1;
				} else if (firstVisibleItem == 0) {
					scrollTopBottompr = 0;
				}
				System.out.println("=========" +scrollTopBottompr);
			}
		});
		actualListView2 = firstcategory2.getRefreshableView();
		if(mGroups != null) {
			getProjects(1);
		}
		
	}

	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title).setMessage(content).setPositiveButton("确定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (content != null && content.trim().equals("用户不存在")) {
					// finish();
				}
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(mContext);
				}

			}
		}).show();
	}

	/**
	 * 获取项目公海数据
	 * 
	 * @param pageIndex
	 */
	private void getProjects(final int pageIndex) {
		Network mNetword = new Network(mContext);
		if(!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else {
			final ProgressDialog progressDialog = ProgressDialog.show(this, "网络数据", "...Loading...");
			// http://crmsoap.woniuwo.cn/projects_of_group?group_id=5374724ed5ac700e4ce8f609
			// &user_id=cd34350bb2844077bfbd4abe5ec56f99
			// &token=15f4b0826dc841198c30088f4a7afd90
			// &validation=gAJ9cQAoVQZsb2NhbGVxAVUFemhfQ05xAl
			// &page=1&t=p
			String URL = Network.API_DOMAIN + "/projects_of_group?group_id=" + mGroups.getGroup_id() + "&user_id=" + user_id + "&token=" + token
					+ "&validation=" + CRMUserBaseInfo.kValication + "&page=" + pageIndex + "&t=p";

			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
				@Override
				public void onResponse(JSONObject response) {
					ProgressDialogUtil.dissmis(progressDialog);
					System.out.println("获取项目公海数据  response=" + response);
					try {
						String user_id = "";
						String token = "";
						Log.e("wop", " response = " + response.toString());
						if(!response.isNull("projects")) {
							String myString = response.get("projects").toString();
							if(myString.equals("[]")) {
								Toast.makeText(mContext, "已经到最后了~", Toast.LENGTH_SHORT).show();
							} else {
								org.json.JSONArray jsonArr;
								if(mProjectsList == null || pageIndex == 1) {
									mProjectsList = new ArrayList<Projects>();
								}
								jsonArr = response.getJSONArray("projects");
								if(jsonArr.length() > 0) {
									for(int i = 0; i < jsonArr.length(); i++) {
										Projects my_project = new Projects();
										JSONObject jsonObj2 = jsonArr.getJSONObject(i);
										if(!jsonObj2.isNull("is_approved")) {
											boolean is_approved = Boolean.valueOf(jsonObj2.getString("is_approved"));
											my_project.setIs_approved(is_approved);
										}
										if(!jsonObj2.isNull("client_id")) {
											String client_id = jsonObj2.getString("client_id");
											my_project.setClient_id(client_id);
										}
										if(!jsonObj2.isNull("project_name")) {
											String project_name = jsonObj2.getString("project_name");
											my_project.setProject_name(project_name);
										}
										if(!jsonObj2.isNull("project_id")) {
											String project_id = jsonObj2.getString("project_id");
											my_project.setProject_id(project_id);
										}
//										if(!jsonObj2.isNull("project_status")) {
//											String project_status = jsonObj2.getString("project_status");
//											my_project.setProcess_status(project_status);
//										}
										my_project.setUser_id(user_id);
										my_project.setToken(token);
										mProjectsList.add(my_project);
									}
								}
								if(!response.isNull("errors")) {
									String errors = response.get("errors").toString();
									if(errors.equals("[]")) {} else {
										org.json.JSONArray jsonArrs;
										if(!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArrs = response.getJSONArray("errors");
											if(jsonArrs.length() > 0) {
												for(int i = 0; i < jsonArrs.length(); i++) {
													JSONObject jsonObj2 = jsonArrs.getJSONObject(i);
													if(!jsonObj2.isNull("desc")) {
														// dismissProgressDialog(progressDialog);
														String desc = jsonObj2.getString("desc");
														openDailog("登录失败提示", desc);
														mLoginError.setDesc(desc);
													}
													if(!jsonObj2.isNull("value")) {
														String value = jsonObj2.getString("value");
														mLoginError.setValue(value);
													}
												}
											}
										}
									}
								}
								mRuAdapter2 = new PageProjectAdapter(mContext, mProjectsList);
								mRuAdapter2.notifyDataSetChanged();
								actualListView2.setAdapter(mRuAdapter2);
								if(pageIndex > 1) {
									actualListView2.setSelection(projectLastPos);
								}
							}
						}
						if (firstcategory2 != null) {
							firstcategory2.onRefreshComplete();
						}
					}
					catch(NumberFormatException e) {
						e.printStackTrace();
					}
					catch(JSONException e) {
						e.printStackTrace();
					}
				}
			}, new Response.ErrorListener() {
				@Override
				public void onErrorResponse(VolleyError arg0) {
					ProgressDialogUtil.dissmis(progressDialog);
					System.out.println("sorry,Error");
				}
			});
			requestQueue.add(jsonObjectRequest);
		}
	}

}
